package com.fatgirl.load.loadStrategy
{
	
	import com.fatgirl.load.LoadData;
	
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	import flash.system.ApplicationDomain;
	import flash.system.LoaderContext;
	import flash.utils.ByteArray;

	/**
	 *  
	 * 二进制加载器
	 * @author iceman
	 * 
	 */
	public class URLLoaderStrategy extends LoadStrategy implements ILoadStrategy
	{
		private var m_URLloader:URLLoader
		private var m_url:String;
		
		public function URLLoaderStrategy()
		{
		}
		
		public override function load(_url:String):void
		{
			m_url = _url;
			m_URLloader = new URLLoader;
			m_URLloader.dataFormat = URLLoaderDataFormat.BINARY;
			var t_request:URLRequest = new URLRequest(_url);
			m_URLloader.addEventListener(Event.COMPLETE,completeHandler);
			m_URLloader.addEventListener(ProgressEvent.PROGRESS,progressHandler);
			m_URLloader.addEventListener(IOErrorEvent.IO_ERROR,ioErrorHandler);
			m_URLloader.addEventListener(Event.OPEN,openHandler);
			m_URLloader.addEventListener(SecurityErrorEvent.SECURITY_ERROR,securityErrorHandler);
			m_URLloader.load(t_request);
		}
		/**
		 * 停止并移除加载 
		 * 
		 */
		public override final function unLoad():void
		{
			removeAllListener();
			m_URLloader.close();
			m_URLloader = null;
		}
		private function completeHandler(e:Event):void
		{
			this.complete(m_URLloader.data);
			unLoad();
		}
		private function progressHandler(e:ProgressEvent):void
		{
			var t_percent:int = ((e.bytesLoaded/e.bytesTotal)*100)>>0;
			this.progress(t_percent);
		}
		private function ioErrorHandler(e:IOErrorEvent):void
		{
			this.ioError(m_url);
			unLoad();
		}
		private function openHandler(e:Event):void
		{
			this.open(m_url);
		}
		private function securityErrorHandler(e:SecurityErrorEvent):void
		{
			this.security(m_url);
			unLoad();
		}
		private function removeAllListener():void
		{
			m_URLloader.removeEventListener(Event.COMPLETE,completeHandler);
			m_URLloader.removeEventListener(ProgressEvent.PROGRESS,progressHandler);
			m_URLloader.removeEventListener(IOErrorEvent.IO_ERROR,ioErrorHandler);
			m_URLloader.removeEventListener(Event.OPEN,openHandler);
			m_URLloader.removeEventListener(SecurityErrorEvent.SECURITY_ERROR,securityErrorHandler);
		}
	}
}